const xss = require('xss');
const {exec, escape} = require('../db/mysql');

const getList = (author, keyword) => {
    let sql = `select *
               from blogs
               where 1 = 1 `;
    if (author) {
        sql += `and author='${author}' `;
    }
    if (keyword) {
        sql += `and title like '%${keyword}%' `;
    }
    sql += `order by createtime desc;`;
    /*返回promise*/
    return exec(sql);
};

const getDetail = id => {
    const sql = `select * from blogs where id=${id}`;
    return exec(sql).then(rows => {
        return rows[0];
    });
};

const newBlog = (blogData = {}) => {
    /*blogData 是一个博客对象，包含 title，content，createTime，author等*/
    let title = xss(blogData.title);
    let content = xss(blogData.content);
    let author = blogData.author;
    const createTime = Date.now();
    const sql = `insert into blogs(title, content, createtime, author)
                 values ('${title}', '${content}', '${createTime}', '${author}');`;
    return exec(sql).then(insertData => {
        return {
            id: insertData.insertId
        }
    });
};

const updateBlog = (id, blogData = {}) => {
    /*id：要更新博客的id*/
    /*blogData 是一个博客对象，包含 title，content*/
    let title = xss(blogData.title);
    let content = xss(blogData.content);
    const sql = `update blogs set title='${title}',content='${content}' where id=${id};`;
    return exec(sql).then(updateData => {
        return updateData.affectedRows > 0;
    })
};

const deleteBlog = (id, author) => {
    /*id：要更新博客的id*/
    author = escape(author);
    const sql = `delete from blogs where id=${id} and author=${author};`;
    return exec(sql).then(deleteData => {
        return deleteData.affectedRows > 0;
    })
};

module.exports = {getList, getDetail, newBlog, updateBlog, deleteBlog};
